import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '@/views/Login'
import Index from '@/views/Index'

Vue.use(VueRouter)

const router = new VueRouter({
  routes: [
    {
      path: '/',
      redirect: '/login'
    },
    {
      path: '/login',
      component: Login
    },
    {
      path: '/index',
      component: Index,
      redirect: '/welcome',
      children: [
        {
          path: '/welcome',
          name: 'Welcome',
          component: () => import('@/views/Welcome')
        },
        {
          path: '/category',
          name: 'Category',
          component: () => import('@/views/Category')
        },
        {
          path: '/course',
          name: 'Course',
          component: () => import('@/views/Course')
        },
        {
          path: '/note',
          name: 'Note',
          component: () => import('@/views/Note')
        },
        {
          path: '/paper',
          name: 'Paper',
          component: () => import('@/views/Paper')
        },
        {
          path: '/subject',
          name: 'Subject',
          component: () => import('@/views/Subject')
        },
        {
          path: '/question',
          name: 'Question',
          component: () => import('@/views/Question')
        },
        {
          path: '/records',
          name: 'Records',
          component: () => import('@/views/Records')
        },
        {
          path: '/user',
          name: 'User',
          component: () => import('@/views/User')
        }
      ]
    }
  ]
})
/**
 * 挂在beforEach导航守卫
 * 相当于后台拦截器进行判定sessionStorage中是否有值
 */
router.beforeEach((to, from, next) => {
  // to:将要访问的路径
  // from:从哪个路径过来
  // next:函数，表示放行操作
  // next()->直接放行; next('/login')->回到登录页
  if (to.path === '/login') {
    return next()
  }
  // 获取token查询是否合法用户
  const token = window.sessionStorage.getItem('token')
  if (!token) {
    return next('/login')
  }
  // 表示token合法，直接放行
  next()
})

export default router
